import React, { useEffect, useRef, useState } from 'react';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { connect } from 'react-redux';
import { View, Text, Image, Textarea } from '@tarojs/components';
import CommentImagePicker from '@/components/Comment/ImagePicker';
import { commentUploadImgServer } from '@/services/comment';
import AddressSelect from '@/pages/mainPages/addressSelect/index';
import TheButton from '@/components/Button';
import SelectLayout from '@/components/SelectLayout/index';
import pGo from '@/images/common/rightGray.png';
import './index.scss';
import ProductInfoAfterSale from '../productInfo/index';

const ApplyDescribe = ({
  handleApplyDescribe = null,
  handleApplyPic = null,
  displaySelect,
  reason,
  className = '',
}) => {
  const [num, setNum] = useState(0);
  const [textAreaFocus, setTextAreaFocus] = useState(false);
  const handleTextArea = (e) => {
    setNum(e.detail.value.length);
    handleApplyDescribe(e.detail.value || '');
  };
  const handleChange = (files) => {
    handleApplyPic(files);
  };

  return (
    <View className={'ApplyDescribe box ' + className}>
      <View className="flex-row-spaceBetween-center">
        <View className="txt32 black085 blod">申请原因</View>
        <View className="flex-row-spaceBetween-center" onClick={() => displaySelect()}>
          <View className={'txt28 ' + (reason?.value ? '' : 'gray')}>
            {reason?.value || '请选择'}
          </View>
          <Image className="arrow" src={pGo} />
        </View>
      </View>
      <View className="addBox flex-column">
        <Textarea
          className="textarea"
          autoHeight
          placeholder="请描述申请售后服务的具体原因"
          placeholderClass="textPlaceHolder"
          maxlength={500}
          cursorSpacing={200}
          onInput={handleTextArea}
          focus={textAreaFocus}
          onBlur={() => setTextAreaFocus(false)}
        />
        <View className="flex-row-end-center num" onClick={() => setTextAreaFocus(true)}>
          {num}/500
        </View>
        <View className="pics">
          <CommentImagePicker onChange={handleChange} limitCount={3} from="afterSale" />
        </View>
        <View className="txt22 tip">若为商品质量问题，必须上传您收到的商品照片</View>
        <View className="txt22 tip">为了帮您更好的解决问题，请务必上传有效凭证</View>
      </View>
    </View>
  );
};

//kind:2退货 3换货
const ConnectInfo = ({
  kind = 2,
  adjustmentBefore = {},
  addr = {},
  setIsOpen = null,
  className = '',
}) => {
  return (
    <View className={'ConnectInfo box ' + className}>
      <View className="txt32 black0 blod">{kind == 2 ? '退货信息' : '换货信息'}</View>
      <View className="flex-row-spaceBetween-center mt25">
        <Text className="txt28">{kind == 2 ? '退货方式' : '返回方式'}</Text>
        <Text className="txt28 black085">自行寄出</Text>
      </View>
      <View className="tipInfo mt16">
        本次需您先行垫付物流费用，由于商品质量问题引起的退换货，可享受运费补偿
      </View>
      {kind == 3 && (
        <View className="flex-row-spaceBetween-center mt32">
          <View className="flex-column lableAddr">
            <View className="txt28">收货地址</View>
          </View>
          <View
            className="flex-column txt28 black085 detail"
            onClick={() => setIsOpen && setIsOpen(true)}
          >
            {Object.keys(addr).length > 0 ? (
              <>
                <View className="flex-row-spaceBetween-center">
                  <Text>{addr.contactName}</Text>
                  <Text>{addr.mobile}</Text>
                </View>
                <View className="mt12">{addr.address + (addr.houseNumber || '')}</View>
              </>
            ) : (
              <View className="textright gray">请选择地址</View>
            )}
          </View>
          <View className="flex-row-center-center">
            <View
              className="flex-row-center-center arrow"
              onClick={() => setIsOpen && setIsOpen(true)}
            >
              <Image className="goAddr" src={pGo} />
            </View>
          </View>
        </View>
      )}
      {kind == 2 && (
        <View className="flex-row-spaceBetween-center mt32">
          <Text className="txt28">退款方式</Text>
          <Text className="txt28 black085">按照原路返还</Text>
        </View>
      )}
      {adjustmentBefore.refundUser && (
        <View className="flex-row-spaceBetween-center mt32">
          <Text className="txt28 black085">联系人：</Text>
          <Text className="txt28 black085">{adjustmentBefore.refundUser}</Text>
        </View>
      )}
      {adjustmentBefore.refundMobile && (
        <View className="flex-row-spaceBetween-center mt32">
          <Text className="txt28 black085">联系人电话：</Text>
          <Text className="txt28 black085">{adjustmentBefore.refundMobile}</Text>
        </View>
      )}
    </View>
  );
};

const BottomArea = ({ handleSubmit, data, reasonMedia }) => {
  const { reason } = data.adjustment;
  let isDisabled = true;
  if (
    reason &&
    (reason.value != '质量问题' || (reason.value == '质量问题' && reasonMedia?.length > 0))
  ) {
    isDisabled = false;
  }
  return (
    <View className="flex-row-center BottomArea">
      <TheButton txt="提交" handleOp={handleSubmit} disabled={isDisabled} />
    </View>
  );
};

//kind:2退货 3换货
const ApplyForAfterSale = ({
  dispatch,
  selectedAddress = {},
  adjustmentBefore = {},
  detail = {},
}) => {
  const [isOpenSelectAddr, setIsOpenSelectAddr] = useState(false);
  const [isOpenSelectReason, setIsOpenSelectReason] = useState(false);
  const [reason, setReason] = useState(null);
  const [reasonMedia, setReasonMedia] = useState([]);
  const [kindText, setKindText] = useState(null);
  const applyParams = useRef({ adjustment: {}, item: {} });
  const router = useRouter();
  const { params = {} } = router;
  let { isModify = false, kind, orderId, orderItemId } = params;
  let productInfo = {};

  const handleApplyAfterSale = () => {
    dispatch({
      type: 'order/applyAfterService',
      payload: {
        kind: kind == 1 ? 1 : 2,
        orderId,
        lineItemId: orderItemId,
      },
    });
  };

  useEffect(() => {
    if (isModify) {
      let remark = detail.merchantRemark || '';
      let oldReason = JSON.parse(detail.reason || '{}');
      setReason(oldReason);
      kind = detail.kind;
      kind == 2 && setKindText('退货商品');
      orderId = detail.orderId;
      orderItemId = detail.orderId && detail?.items[0]?.orderItemId;
      let reasonMediaOrg = JSON.parse(detail.reasonMedia || '[]');
      setReasonMedia(reasonMediaOrg);
      applyParams.current = {
        adjustment: {
          kind,
          orderId,
          reason: oldReason,
          customRemark: remark,
          reasonMedia: reasonMediaOrg,
          orderAdjustId: detail.id,
        },
        item: { orderItemId, refundQuantity: 1 },
      };
    } else {
      applyParams.current = {
        adjustment: { kind, orderId },
        item: { orderItemId, refundQuantity: 1 },
      };
    }
    handleApplyAfterSale();
  }, []);

  useEffect(() => {
    if (Object.keys(adjustmentBefore).length > 0 && isModify) {
      applyParams.current.item.refundQuantity =
        adjustmentBefore?.itemList[0]?.hasRefundQuantity || 1;
    }
  }, [adjustmentBefore]);

  useDidShow(() => {
    if (kind == 3) {
      Taro.setNavigationBarTitle({
        title: '申请换货',
      });
    }
  });
  const handleApplyReason = (item) => {
    setReason(item);
    applyParams.current.adjustment.reason = item;
  };

  const handleApplyDescribe = (item) => {
    applyParams.current.adjustment.customRemark = item;
  };

  const handleApplyPic = (item) => {
    setReasonMedia([...item]);
    applyParams.current.adjustment.reasonMedia = [...item];
  };

  const handleProductNum = (num) => {
    applyParams.current.item.refundQuantity = num;
  };

  const handleSubmit = async () => {
    if (applyParams.current.adjustment?.customRemark?.length > 500) {
      Taro.showToast({
        title: '申请原因描述文字过长',
        duration: 2000,
        icon: 'none',
      });
      return;
    }
    const { adjustment = {}, item = {} } = applyParams.current;
    let files = [];
    const imgUrls = adjustment.reasonMedia || [];
    if (imgUrls.length < 1) {
      Taro.showToast({
        title: '必须上传商品图片',
        duration: 2000,
        icon: 'none',
      });
      return;
    }
    for (let file of imgUrls) {
      const fileRes = await commentUploadImgServer(file);
      if (fileRes.code == 1 && fileRes.content) {
        files.push(fileRes.content);
      }
    }
    adjustment.reasonMedia = files;

    if (adjustment.reason?.value == '质量问题' && files.length == 0) {
      Taro.showToast({
        title: '商品质量问题，必须上传您收到的商品照片',
        duration: 2600,
        icon: 'none',
      });
      return;
    }

    dispatch({
      type: 'order/applyRefund',
      payload: {
        adjustment,
        item,
      },
    });
  };

  if (Object.keys(adjustmentBefore).length > 0) {
    productInfo = adjustmentBefore?.itemList[0];
  }

  return (
    <View className="ApplyForAfterSale">
      <SelectLayout
        isOpened={isOpenSelectReason}
        reasonList={adjustmentBefore.reasonList || []}
        title="申请理由"
        btnTxt="提交"
        handleClose={() => setIsOpenSelectReason(false)}
        handleSelected={handleApplyReason}
      />
      <AddressSelect isOpened={isOpenSelectAddr} handleClose={() => setIsOpenSelectAddr(false)} />
      <ProductInfoAfterSale
        className="mt20"
        product={productInfo}
        title={kindText ? kindText : kind == 2 ? '退货商品' : '换货商品'}
        handleNum={handleProductNum}
      />
      <ApplyDescribe
        className="mt20"
        handleApplyDescribe={handleApplyDescribe}
        handleApplyPic={handleApplyPic}
        displaySelect={() => setIsOpenSelectReason(true)}
        reason={reason}
      />
      <ConnectInfo
        className="mt20 mb186"
        kind={kind}
        adjustmentBefore={adjustmentBefore}
        addr={selectedAddress}
        setIsOpen={kind == 2 ? null : setIsOpenSelectAddr}
      />
      <BottomArea
        handleSubmit={handleSubmit}
        data={applyParams.current}
        reasonMedia={reasonMedia}
      />
    </View>
  );
};

export default connect(({ productCar, order }) => ({
  selectedAddress: productCar.selectedAddress,
  adjustmentBefore: order.adjustmentBefore,
  detail: order.adjustmentDetail,
}))(ApplyForAfterSale);
